package com.test.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.test.getfile.*;
/**
 * Servlet implementation class image_svr
 */
public class image_svr extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public image_svr() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		TestFile tf = new TestFile();
		tf.GetFilePath("D:/1");
		
		request.setCharacterEncoding("UTF-8");
		String strImageIndex = request.getParameter("imgnum");
		int imgnum;
		if(null == strImageIndex)
		{
			imgnum = 0;
		}else
		{
			imgnum = Integer.parseInt(strImageIndex);
		}		
		
		String path = tf.getCurrentPath(imgnum);
		response.setContentType("image/jpeg");
		ServletOutputStream sos = response.getOutputStream();
		InputStream is = null;
		response.setContentType("image/gif");
		try 
		{			
			is = new FileInputStream(path);
			BufferedInputStream bis = new BufferedInputStream(is);
			BufferedOutputStream bos = new BufferedOutputStream(sos);
		 
			byte[] data = new byte[4096];
			int size = -1;
			while ((size = bis.read(data)) != -1)
			{
				
				bos.write(data, 0, size);
			}
			bos.flush();
		}
		catch (Exception ex) 
		{
			ex.printStackTrace();
		}
		finally 
		{
			if (null != is) 
			{
				is.close();
			}
			if (null != sos) 
			{
				sos.close();
			}
		}	
	}
}
